import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import * as fromRoot from '../reducers';
import { Store } from '@ngrx/store';
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private store$: Store<fromRoot.State>, private router: Router) { }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> {
    // return Observable.of(true);
    return this.store$.select(fromRoot.getAuthState)
      .map(auth => {
        const result = auth.token !== null && auth.token !== undefined;
        if (result) {
          this.router.navigate(['/login']);
        }
        return result;
      })
      .defaultIfEmpty(false);
  }
}
